<template>
  <MainLayout>
    <div class="classes-page">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-background"></div>
        <div class="header-content">
          <div class="header-left">
            <div class="header-icon">
              <el-icon size="32"><School /></el-icon>
            </div>
            <div class="header-text">
              <h1>班级管理</h1>
              <p>创建和管理班级，组织学生，提升教学效果</p>
            </div>
          </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              size="large" 
              @click="loadClasses" 
              class="action-btn primary-btn"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button
              v-if="isTeacher"
              type="success"
              size="large"
              @click="showCreateDialog = true"
              class="action-btn success-btn"
            >
              <el-icon><Plus /></el-icon>
              创建班级
            </el-button>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon total-icon">
                <el-icon size="24"><School /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ classes.length }}</div>
                <div class="stat-label">总班级数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon active-icon">
                <el-icon size="24"><Check /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ activeClassesCount }}</div>
                <div class="stat-label">活跃班级</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon students-icon">
                <el-icon size="24"><User /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ totalStudents }}</div>
                <div class="stat-label">总学生数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon capacity-icon">
                <el-icon size="24"><TrendCharts /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ averageCapacity }}%</div>
                <div class="stat-label">平均容量</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 班级列表 -->
      <el-card class="classes-table-card" shadow="hover">
        <template #header>
          <div class="table-header">
            <div class="header-left">
              <el-icon size="20" class="table-icon"><List /></el-icon>
              <span class="table-title">班级列表</span>
              <el-tag type="info" size="small">{{ classes.length }} 个班级</el-tag>
            </div>
            <div class="header-actions">
              <el-button text @click="loadClasses" class="refresh-btn">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table 
          :data="classes" 
          v-loading="loading" 
          style="width: 100%"
          class="classes-table"
          :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
          stripe
        >
          <el-table-column prop="id" label="ID" width="80" align="center">
            <template #default="{ row }">
              <span class="class-id">#{{ row.id }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="班级信息" min-width="300">
            <template #default="{ row }">
              <div class="class-info">
                <div class="class-header">
                  <div class="class-icon">
                    <el-icon size="20"><School /></el-icon>
                  </div>
                  <div class="class-details">
                    <h4 class="class-name">{{ row.name }}</h4>
                    <p class="class-description">{{ row.description || '暂无描述' }}</p>
                  </div>
                </div>
                <div class="class-meta">
                  <el-tag 
                    :type="row.status === 'active' ? 'success' : 'info'" 
                    size="small"
                    class="status-tag"
                  >
                    <el-icon size="12">
                      <component :is="row.status === 'active' ? 'Check' : 'InfoFilled'" />
                    </el-icon>
                    {{ row.status === 'active' ? '活跃' : '停用' }}
                  </el-tag>
                  <span class="created-time">
                    <el-icon size="14"><Calendar /></el-icon>
                    {{ formatDate(row.created_at) }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="学生容量" width="150" align="center">
            <template #default="{ row }">
              <div class="capacity-info">
                <div class="capacity-bar">
                  <div class="capacity-progress">
                    <div 
                      class="capacity-fill" 
                      :style="{ width: `${(row.current_students / row.max_students) * 100}%` }"
                      :class="{ 'full': row.current_students >= row.max_students }"
                    ></div>
                  </div>
                </div>
                <div class="capacity-text">
                  <el-tag 
                    :type="row.current_students >= row.max_students ? 'danger' : 'success'"
                    size="small"
                  >
                    {{ row.current_students }}/{{ row.max_students }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="280" align="center" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  size="small"
                  type="primary"
                  text 
                  @click="viewClassDetail(row)"
                  class="action-btn"
                >
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button
                  size="small"
                  type="warning"
                  text
                  @click="editClass(row)"
                  class="action-btn"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="success"
                  text
                  @click="manageStudents(row)"
                  class="action-btn"
                >
                  <el-icon><User /></el-icon>
                  管理学生
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="classes.length === 0 && !loading" class="empty-state">
          <el-empty 
            description="暂无班级数据" 
            :image-size="120"
          >
            <el-button type="primary" @click="showCreateDialog = true" v-if="isTeacher">
              <el-icon><Plus /></el-icon>
              创建第一个班级
            </el-button>
          </el-empty>
        </div>
      </el-card>

    <!-- 创建班级对话框 -->
    <el-dialog v-model="showCreateDialog" title="创建班级" width="500px">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input v-model="createForm.description" type="textarea" :rows="3" placeholder="请输入班级描述" />
        </el-form-item>
        <el-form-item label="最大学生数" prop="max_students">
          <el-input-number v-model="createForm.max_students" :min="1" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createClass" :loading="creating">创建</el-button>
      </template>
    </el-dialog>

    <!-- 编辑班级对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑班级" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" :rows="3" placeholder="请输入班级描述" />
        </el-form-item>
        <el-form-item label="最大学生数" prop="max_students">
          <el-input-number v-model="editForm.max_students" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status">
            <el-option label="活跃" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="updateClass" :loading="updating">保存</el-button>
      </template>
    </el-dialog>

    <!-- 管理学生对话框 -->
    <el-dialog v-model="showStudentsDialog" title="管理学生" width="800px">
      <div class="students-management">
        <div class="students-section">
          <h4>当前学生 ({{ currentClass?.students?.length || 0 }})</h4>
          <el-table :data="currentClass?.students || []" style="width: 100%">
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="removeStudent(row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="add-students-section">
          <h4>添加学生</h4>
          <el-select v-model="selectedStudents" multiple placeholder="选择要添加的学生" style="width: 100%">
            <el-option
              v-for="student in availableStudents"
              :key="student.id"
              :label="student.name"
              :value="student.id"
            />
          </el-select>
          <el-button type="primary" @click="addStudents" :loading="addingStudents" style="margin-top: 10px">
            添加学生
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, School, Check, User, TrendCharts, Filter, Search, List, Edit, View, Delete, Calendar, InfoFilled } from '@element-plus/icons-vue'
import { classesApi, type Class, type CreateClassRequest, type UpdateClassRequest } from '@/api/classes'
import { useAuthStore } from '@/stores/auth'
import MainLayout from '@/layouts/MainLayout.vue'

const authStore = useAuthStore()
const isTeacher = computed(() => authStore.user?.role === 'teacher')

// 数据
const classes = ref<Class[]>([])
const loading = ref(false)
const creating = ref(false)
const updating = ref(false)
const addingStudents = ref(false)

// 筛选和搜索
const searchQuery = ref('')
const statusFilter = ref('')
const capacityFilter = ref('')

// 对话框状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showStudentsDialog = ref(false)

// 表单数据
const createForm = ref<CreateClassRequest>({
  name: '',
  description: '',
  max_students: 50
})

const editForm = ref<UpdateClassRequest>({})
const currentClass = ref<ExtendedClass | null>(null)
const selectedStudents = ref<number[]>([])
const availableStudents = ref<any[]>([])

// 表单规则
const createRules = {
  name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }]
}

const editRules = {
  name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }]
}

// 表单引用
const createFormRef = ref()
const editFormRef = ref()

// 扩展Class接口以包含students属性
interface ExtendedClass extends Class {
  students?: any[]
}

// 计算属性
const activeClassesCount = computed(() => {
  return classes.value.filter(item => item.status === 'active').length
})

const totalStudents = computed(() => {
  return classes.value.reduce((sum, item) => sum + item.current_students, 0)
})

const averageCapacity = computed(() => {
  if (classes.value.length === 0) return 0
  const totalCapacity = classes.value.reduce((sum, item) => sum + item.max_students, 0)
  const totalStudents = classes.value.reduce((sum, item) => sum + item.current_students, 0)
  return Math.round((totalStudents / totalCapacity) * 100)
})

// 加载班级列表
const loadClasses = async () => {
  loading.value = true
  try {
    const response = await classesApi.getClasses()
    classes.value = response
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '加载班级列表失败')
  } finally {
    loading.value = false
  }
}

// 创建班级
const createClass = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      creating.value = true
      try {
        await classesApi.createClass(createForm.value)
        ElMessage.success('创建班级成功')
        showCreateDialog.value = false
        createForm.value = { name: '', description: '', max_students: 50 }
        loadClasses()
      } catch (error: any) {
        ElMessage.error(error.response?.data?.error || '创建班级失败')
      } finally {
        creating.value = false
      }
    }
  })
}

// 编辑班级
const editClass = (classData: Class) => {
  editForm.value = {
    name: classData.name,
    description: classData.description,
    max_students: classData.max_students,
    status: classData.status
  }
  currentClass.value = classData
  showEditDialog.value = true
}

// 更新班级
const updateClass = async () => {
  if (!editFormRef.value || !currentClass.value) return
  
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      updating.value = true
      try {
        const classId = currentClass.value?.id
        if (!classId) {
          ElMessage.error('班级ID不存在')
          return
        }
        await classesApi.updateClass(classId, editForm.value)
        ElMessage.success('更新班级成功')
        showEditDialog.value = false
        loadClasses()
      } catch (error: any) {
        ElMessage.error(error.response?.data?.error || '更新班级失败')
      } finally {
        updating.value = false
      }
    }
  })
}

// 查看班级详情
const viewClassDetail = (classData: Class) => {
  // 这里可以跳转到班级详情页面或显示详情对话框
  ElMessage.info(`查看班级: ${classData.name}`)
}

// 管理学生
const manageStudents = async (classData: Class) => {
  currentClass.value = classData
  showStudentsDialog.value = true
  
  // 加载班级详情和学生列表
  try {
    const response = await classesApi.getClassDetail(classData.id)
    currentClass.value = response
    
    // 这里应该加载可用的学生列表（未加入该班级的学生）
    // 暂时使用模拟数据
    availableStudents.value = []
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '加载班级详情失败')
  }
}

// 添加学生
const addStudents = async () => {
  if (!currentClass.value || selectedStudents.value.length === 0) return
  
  addingStudents.value = true
  try {
    const classId = currentClass.value?.id
    if (!classId) {
      ElMessage.error('班级ID不存在')
      return
    }
    await classesApi.addStudents(classId, {
      student_ids: selectedStudents.value
    })
    ElMessage.success('添加学生成功')
    selectedStudents.value = []
    manageStudents(currentClass.value)
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '添加学生失败')
  } finally {
    addingStudents.value = false
  }
}

// 移除学生
const removeStudent = async (student: any) => {
  if (!currentClass.value) return
  
  try {
    await ElMessageBox.confirm(`确定要移除学生 ${student.name} 吗？`, '确认移除', {
      type: 'warning'
    })
    
    const classId = currentClass.value?.id
    if (!classId) {
      ElMessage.error('班级ID不存在')
      return
    }
    await classesApi.removeStudent(classId, student.id)
    ElMessage.success('移除学生成功')
    manageStudents(currentClass.value)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.error || '移除学生失败')
    }
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取过滤后的班级列表
const filteredClasses = computed(() => {
  let filtered = classes.value
  
  if (searchQuery.value) {
    filtered = filtered.filter(
      (item) =>
        item.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        (item.description && item.description.toLowerCase().includes(searchQuery.value.toLowerCase()))
    )
  }

  if (statusFilter.value) {
    filtered = filtered.filter((item) => item.status === statusFilter.value)
  }

  if (capacityFilter.value) {
    filtered = filtered.filter((item) => {
      if (capacityFilter.value === 'available') {
        return item.current_students < item.max_students
      } else if (capacityFilter.value === 'full') {
        return item.current_students >= item.max_students
      }
      return true
    })
  }
  
  return filtered
})

// 扩展Class接口以包含students属性
interface ExtendedClass extends Class {
  students?: any[]
}

onMounted(() => {
  loadClasses()
})
</script>

<style scoped>
.classes-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  position: relative;
  height: 250px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.3;
}

.header-content {
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 90%;
  max-width: 1200px;
  margin: 0 auto;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 15px;
  margin-right: 20px;
  backdrop-filter: blur(10px);
}

.header-text h1 {
  margin: 0 0 10px 0;
  font-size: 36px;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.header-text p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}

.header-actions {
  display: flex;
  gap: 15px;
}

.action-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  border: none;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.primary-btn {
  background-color: #409eff;
  color: white;
}

.primary-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

.success-btn {
  background-color: #67c23a;
  color: white;
}

.success-btn:hover {
  background-color: #85ce61;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
}

.stats-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  background: linear-gradient(135deg, #fdf6ec 0%, #faecd8 100%);
  border: 1px solid #faecd8;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(230, 162, 60, 0.2);
}

.stat-icon {
  margin-right: 15px;
  padding: 12px;
  border-radius: 50%;
  background-color: rgba(230, 162, 60, 0.1);
}

.total-icon {
  color: #e6a23c;
}

.active-icon {
  color: #67c23a;
}

.students-icon {
  color: #409eff;
}

.capacity-icon {
  color: #909399;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.classes-table-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-icon {
  color: #409eff;
  font-size: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.refresh-btn {
  color: #909399;
  transition: color 0.3s ease;
}

.refresh-btn:hover {
  color: #409eff;
}

.classes-table {
  width: 100%;
}

.classes-table .el-table__header-wrapper th {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: bold;
  padding: 16px 0;
}

.class-id {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.class-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.class-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.class-icon {
  color: #409eff;
  font-size: 20px;
}

.class-name {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.class-description {
  margin: 0;
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
}

.class-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.created-time {
  display: flex;
  align-items: center;
  gap: 4px;
}

.capacity-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.capacity-bar {
  width: 80px;
  height: 6px;
  background-color: #ebeef5;
  border-radius: 3px;
  overflow: hidden;
}

.capacity-progress {
  height: 100%;
  background-color: #409eff;
  border-radius: 3px;
  transition: width 0.3s ease-in-out;
}

.capacity-fill {
  height: 100%;
  background-color: #67c23a;
  border-radius: 3px;
  transition: width 0.3s ease-in-out;
}

.capacity-fill.full {
  background-color: #f56c6c;
}

.capacity-text {
  font-size: 12px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background-color: #ecf5ff;
  color: #409eff;
  transform: translateY(-1px);
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-state .el-empty__description {
  color: #909399;
  font-size: 16px;
}

.empty-state .el-button {
  margin-top: 20px;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
}

.students-management {
  display: flex;
  gap: 20px;
  padding: 20px;
}

.students-section,
.add-students-section {
  flex: 1;
  background-color: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.students-section h4,
.add-students-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}
</style>
